package com.lc.zpyh.ui.activity.supermarket;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.widget.layout.SettingBar;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.bean.TimeBean;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.PlaceAnOrderApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.SelectApprovedDeliveryTimeApi;
import com.lc.zpyh.http.request.SelectCabinetryBySchoolApi;
import com.lc.zpyh.http.request.SelectUserCounpsUsableApi;
import com.lc.zpyh.http.request.UpdateAdderssApi;
import com.lc.zpyh.http.response.AddOrderBean;
import com.lc.zpyh.http.response.SelectAddressServiceeBean;
import com.lc.zpyh.http.response.SelectApprovedDeliveryTimeBean;
import com.lc.zpyh.http.response.SelectCabinetryBySchoolBean;
import com.lc.zpyh.http.response.SelectToBeConfirmedBean;
import com.lc.zpyh.http.response.SelectUserCounpsUsableBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.mine.MineAddressManagementActivity;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.BtnUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.view.CouponDialog;
import com.lc.zpyh.view.JiGuiPopupWindow;
import com.lc.zpyh.view.ServiceTimeDialog;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConfirmOrderActivity extends AppActivity {
    private static final String TAG = "ConfirmOrderActivity";
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.tv_phone)
    TextView tvPhone;

    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_check_jigui)
    TextView tvCheckJigui;
    @BindView(R.id.cl_address)
    RelativeLayout clAddress;
    @BindView(R.id.cl_address_emty)
    RelativeLayout clAddressEmty;

    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    @BindView(R.id.sb_yuyueshijian)
    SettingBar sbYuyueshijian;
    @BindView(R.id.tv_total_peisongfei)
    TextView tvTotalPeisongfei;
    @BindView(R.id.rv_peisongfei)
    RecyclerView rvPeisongfei;
    @BindView(R.id.sb_total_money)
    SettingBar sbTotalMoney;
    @BindView(R.id.sb_coupon)
    SettingBar sbCoupon;
    @BindView(R.id.nestedscrollview)
    NestedScrollView nestedscrollview;
    @BindView(R.id.tv_final_price)
    TextView tvFinalPrice;
    @BindView(R.id.btn_submit_order)
    AppCompatButton btnSubmitOrder;
    @BindView(R.id.sb_jianmian_money)
    SettingBar sbJianmianMoney;
    private String cabinetryId = "0";
    private String patientia="1";
    List<SelectToBeConfirmedBean.ListBean.CanteensBean> dataoneList = new ArrayList<>();
    List<SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean> datatwoList = new ArrayList<>();
//商家id 集合
    private List<String> timeList = new ArrayList<>();
    //食堂id 集合
    private List<String> canteeniList = new ArrayList<>();
    //食堂总价 集合
    private List<String> canteenSumList = new ArrayList<>();
    //商家总价 集合
    private List<String> merchontSumList = new ArrayList<>();
    //购物车ids 集合
    private List<String> cartIdsList = new ArrayList<>();
    //备注 集合
    private List<String> infosList = new ArrayList<>();
    private List<String> xiaoliaoList = new ArrayList<>();
    List<SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean.CartsBean> datathreeList = new ArrayList<>();
    private BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean, BaseViewHolder> oneAdapter;
    private JiGuiPopupWindow jiGuiPopupWindow;
    private TextView tv_beizhu;
    private BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean, BaseViewHolder> shangjiaadapter;
    private int pos;
    private ServiceTimeDialog serviceTimeDialog;
    List<TimeBean> datedataList = new ArrayList<>();
    List<SelectUserCounpsUsableBean.ListBean> coupondataList = new ArrayList<>();
    private SelectToBeConfirmedBean.ListBean orderList = null;
    private long nowcal;
    SelectAddressServiceeBean.ListBean addressBean = null;
    private String couponID="";
    private String cartIdS;
    private String addressId;
    private String yytime="";
    private String couponprice="0";
    private double finalprice=0;
    private String userName;
    private String infos;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_confirmorder;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        /**
         * 获取订单数据源
         */

        cartIdS = getIntent().getStringExtra("cartIds");
        Log.e(TAG, "onCreate: "+ cartIdS);
        orderList = (SelectToBeConfirmedBean.ListBean) getIntent().getSerializableExtra("orderList");
        if (orderList != null) {
            for (SelectToBeConfirmedBean.ListBean.CanteensBean bean : orderList.getCanteens()) {
                dataoneList.add(bean);
                for (SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean merchantBean : bean.getMerchant()) {
                    datatwoList.add(merchantBean);
                    for (SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean.CartsBean cartsBean : merchantBean.getCarts()) {
                        datathreeList.add(cartsBean);
                    }
                }
            }
//            优惠券
            selectUserCounpsUsable();

            sbYuyueshijian.setRightText("立即送达");
            sbTotalMoney.setRightText("￥" + BigDecimalUtils.div(orderList.getZj() + "","100",2)+ "");
            tvTotalPeisongfei.setText("￥" + BigDecimalUtils.div(orderList.getZyf() + "","100",2));
            sbJianmianMoney.setRightText("-￥"+BigDecimalUtils.add(orderList.getZjm() + "","0",2));
            tvFinalPrice.setText("￥" +  BigDecimalUtils.div(orderList.getSjjg() + "","100",2) );
            finalprice=Double.parseDouble(BigDecimalUtils.div(orderList.getSjjg() + "","100",2) );
            /**
             * 地址
             */

            if (orderList.getAddress() != null) {
                userName = orderList.getAddress().getName();
                tvUser.setText("收货人："+orderList.getAddress().getName());

                tvPhone.setText(orderList.getAddress().getPhone());
                tvAddress.setText("收货地址："+orderList.getAddress().getCabinetryName());
                addressId = orderList.getAddress().getTheGoodsId()+"";
                clAddress.setVisibility(View.VISIBLE);

            } else {
                clAddressEmty.setVisibility(View.VISIBLE);
            }
        }
/**
 * 预约时间数据计算
 */





//選擇机柜
        setJiGui();
//        外卖列表
        xiaoliaoList.clear();
        rvData();


    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    //代金券
    private void selectUserCounpsUsable() {
        timeList.clear();
        for (int i = 0; i < orderList.getCanteens().size(); i++) {
            canteeniList.add(orderList.getCanteens().get(i).getCanteenId() + "");
            canteenSumList.add(orderList.getCanteens().get(i).getStzj() + "");
            for (int j = 0; j < orderList.getCanteens().get(i).getMerchant().size(); j++) {
                timeList.add(orderList.getCanteens().get(i).getMerchant().get(j).getMerchantId() + "");
                merchontSumList.add(orderList.getCanteens().get(i).getMerchant().get(j).getSjzj() + "");

            }

        }

        EasyHttp.post(this)
                .api(new SelectUserCounpsUsableApi().setCanteenids(CourseUtils.listToString1(canteeniList)).setCanteenSum(CourseUtils.listToString1(canteenSumList)).setMerchantids(CourseUtils.listToString1(timeList)).setMerchontSum(CourseUtils.listToString1(merchontSumList)).setUserid(SPUtil.get(ConfirmOrderActivity.this,IntentKey.USERID,""))).request(new HttpCallback<SelectUserCounpsUsableBean>(this) {

            @Override
            public void onSucceed(SelectUserCounpsUsableBean data) {
                if (data.getCode() == 0) {
                    coupondataList.clear();
                    coupondataList.addAll(data.getList());

                    if (data.getList().size()>0){
                        sbCoupon.setRightText("可用优惠券");
                        sbCoupon.setEnabled(true);
                    }else {
                        sbCoupon.setRightText("暂无可用优惠券");
                        sbCoupon.setEnabled(false);
                    }
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }


    private void rvData() {

if (oneAdapter==null) {
    oneAdapter = new BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean,
            BaseViewHolder>(R.layout.item_shop_confirm_order, orderList.getCanteens()) {

        @Override
        protected void convert(BaseViewHolder holder, SelectToBeConfirmedBean.ListBean.CanteensBean bean) {

            holder.setText(R.id.tv_shitang, bean.getCanteenName());
            RecyclerView rvMixAttr = holder.getView(R.id.rv_shitang);

            shangjiaadapter = new BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean, BaseViewHolder>(R.layout.item_shop_confirm_shangjia, bean.getMerchant()) {
                @Override
                protected void convert(BaseViewHolder holder, SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean merchantbean) {

                    holder.setText(R.id.tv_shangjiamingcheng, merchantbean.getMerchantName());
                    holder.setText(R.id.tv_beizhu, merchantbean.getBeizhu());
                    tv_beizhu = holder.getView(R.id.tv_beizhu);
                    holder.getView(R.id.tv_shangjiamingcheng).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", merchantbean.getMerchantId()+""));
                        }
                    });
                    holder.getView(R.id.rl_beizhu).setOnClickListener(view -> {
                        pos = holder.getPosition();
                        Intent intent = new Intent(ConfirmOrderActivity.this, RemarksActivity.class).putExtra("beizhu",merchantbean.getBeizhu()).putExtra("merchantId", merchantbean.getMerchantId()+"");
                        startActivityForResult(intent, 90);

//                             dataBeanList.remove(childViewHolder.getAbsoluteAdapterPosition());
//                             childViewHolder.getBindingAdapter().notifyDataSetChanged();
                    });

                    RecyclerView rvShangjia = holder.getView(R.id.rv_shangjia);
                    BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean.CartsBean, BaseViewHolder> sjadapter = new BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean.CartsBean, BaseViewHolder>(R.layout.item_shop_confirm_shangjia_order, merchantbean.getCarts()) {
                        @Override
                        protected void convert(@NotNull BaseViewHolder baseViewHolder, SelectToBeConfirmedBean.ListBean.CanteensBean.MerchantBean.CartsBean cartsBean) {
                            GlideApp.with(ConfirmOrderActivity.this).load(IntentKey.ORDER_IMAGE+cartsBean.getImg()).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01)).into((ImageView) baseViewHolder.getView(R.id.img_dianpu));

                            baseViewHolder.setText(R.id.goods, cartsBean.getCommodityName());
                            baseViewHolder.setText(R.id.tv_num, "x" + cartsBean.getCount() + "");
                            int xlprice=0;
                            if (cartsBean.getXl()!=null&&cartsBean.getXl().size()>0) {
                                for (int i = 0; i <cartsBean.getXl().size() ; i++) {
                                    xlprice = xlprice+cartsBean.getXl().get(i).getPrice();
                                    xiaoliaoList.add(cartsBean.getXl().get(i).getTitle());
                                }

                            }
                            if (cartsBean.getGgzjg() != null) {
                                baseViewHolder.setText(R.id.tv_xianjia, "￥" + BigDecimalUtils.add(BigDecimalUtils.div(cartsBean.getGgzjg() + "", "100", 2) + "",BigDecimalUtils.div(xlprice+ "", "100", 2) + "",2));
                            } else {
                                if (cartsBean.getSpjg() != null) {
                                    baseViewHolder.setText(R.id.tv_xianjia, "￥" + BigDecimalUtils.add(BigDecimalUtils.div(cartsBean.getSpjg() + "", "100", 2) + "",BigDecimalUtils.div(xlprice+ "", "100", 2) + "",2));

                                } else {
                                    if (cartsBean.getSpyjg() != null) {
                                        baseViewHolder.setText(R.id.tv_xianjia, "￥" + BigDecimalUtils.add(BigDecimalUtils.div(cartsBean.getSpyjg() + "", "100", 2) + "",BigDecimalUtils.div(xlprice+ "", "100", 2) + "",2));
                                    }
                                }
                            }

                            if (cartsBean.getNameOne() != null) {
                                baseViewHolder.setText(R.id.tv_yueshou, cartsBean.getNameOne()+"  "+CourseUtils.listToString1(xiaoliaoList));
                            }
                            if (cartsBean.getNameTwo() != null) {
                                baseViewHolder.setText(R.id.tv_yueshou, cartsBean.getNameOne() + "、" + cartsBean.getNameTwo()+"  "+CourseUtils.listToString1(xiaoliaoList));
                           }
                            if (cartsBean.getNameOne()==null&&cartsBean.getNameTwo() == null&&xiaoliaoList.size()>0){
                                baseViewHolder.setText(R.id.tv_yueshou,CourseUtils.listToString1(xiaoliaoList));
                            }

                        }
                    };
                    rvShangjia.setAdapter(sjadapter);

                }
            };
            rvMixAttr.setAdapter(shangjiaadapter);
//            ((BaseQuickAdapter<SelectToBeConfirmedBean.ListBean.CanteensBean, BaseViewHolder>) rvMixAttr.getAdapter()).setOnItemClickListener((baseQuickAdapter, view, i) -> {
//
//                startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", shangjiaadapter.getData().get(holder.getPosition()).getMerchantId()+""));

//            });

        }


    };
    rvGoods.setAdapter(oneAdapter);
}else {oneAdapter.notifyDataSetChanged();}
    }

    private void selectApprovedDeliveryTime() {
        timeList.clear();
        if (datatwoList.size() > 0) {
            for (int i = 0; i < datatwoList.size(); i++) {

                timeList.add(datatwoList.get(i).getMerchantId() + "");
            }
        }
        Log.e(TAG, "selectApprovedDeliveryTime: "+addressId );
        EasyHttp.post(this)
                .api(new SelectApprovedDeliveryTimeApi().setMerchantids(CourseUtils.listToString1(timeList)).setAddressId(addressId)).request(new HttpCallback<SelectApprovedDeliveryTimeBean>(this) {

            @Override
            public void onSucceed(SelectApprovedDeliveryTimeBean data) {
                if (data.getCode() == 0) {
                    datedataList.clear();
                    Log.e(TAG, "onSucceed: " + CourseUtils.date2TimeStamp("2021-07-21 19:30:00", "yyyy-MM-dd HH:mm:ss"));
                    nowcal = Calendar.getInstance().getTimeInMillis() / 1000;
                    getDate(nowcal);
                    int timecha = Integer.parseInt(BigDecimalUtils.sub(CourseUtils.date2TimeStamp(getDate(nowcal) + " " + data.getList().getApprovedDeliveryTime(), "yyyy-MM-dd HH:mm:ss"), nowcal + "", 0) + "");
                    if (timecha > 0) {
                        double sum=timecha/(data.getList().getIntervalTime() * 60);
                        Math.floor(sum);
//                        int sum = Integer.parseInt(BigDecimalUtils.div(timecha + "", (data.getList().getIntervalTime() * 60) + "", 0) + "");
                        Log.e(TAG, "onSucceed: " + sum + "");
                        for (int i = 0; i < sum; i++) {
                            TimeBean timeBean=new TimeBean();
                            timeBean.setTime(nowcal + (i+1) * 1200);
                            timeBean.setIsgrop(false);
                            datedataList.add(timeBean);
                        }
                    }
//                     if (datedataList.size()>0){
//                         yytime=getDate1(datedataList.get(0).getTime());
//                     }
                    sbYuyueshijian.setEnabled(true);

                    serviceTimeDialog = new ServiceTimeDialog(ConfirmOrderActivity.this, datedataList);
                    serviceTimeDialog.show();
                    serviceTimeDialog.setOnGoodsOrderListener(new ServiceTimeDialog.OnGoodsOrderListener() {
                        @Override
                        public void onDismiss(String time) {

                        }

                        @Override
                        public void onBuyNow(String time,String lijitime) {
                            if (lijitime.equals("立即送达")){
                                yytime ="";
                            }else {
                                yytime = time;
                            }

                            sbYuyueshijian.setRightText(lijitime);
                        }
                    });
                }else {

                     toast(data.getMsg());

                }

            }

            @Override
            public void onFail(Exception e) {
//                super.onFail(e);
                sbYuyueshijian.setEnabled(false);
            }
        });
    }

    private String getDate(long milliSeconds) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // Create a calendar object that will convert the date and time value in
        // milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds * 1000L);
        return formatter.format(calendar.getTime());
    }
    private String getDate1(long milliSeconds) {

        SimpleDateFormat formatter = new SimpleDateFormat("H:mm");
        // Create a calendar object that will convert the date and time value in
        // milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds * 1000L);
        return formatter.format(calendar.getTime());
    }
    private void setJiGui() {
        EasyHttp.post(this)
                .api(new SelectCabinetryBySchoolApi().setSchoolid(SPUtil.get(this, IntentKey.ADDRESSID, ""))).request(new HttpCallback<SelectCabinetryBySchoolBean>(this) {

            @Override
            public void onSucceed(SelectCabinetryBySchoolBean data) {
//
                if (data.getCode() == 0) {
                    jiGuiPopupWindow = new JiGuiPopupWindow(getContext(), data.getList(), Integer.parseInt(cabinetryId));

                    jiGuiPopupWindow.setOnItemLickenter(new JiGuiPopupWindow.OnItemLickenter() {
                        @Override
                        public void onTypeClick(String type, String id) {
                            tvAddress.setText("收货地址："+type);
                            cabinetryId = id;
                            UpdateAddress();
                        }
                    });
                }


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @OnClick({R.id.tv_check_jigui, R.id.cl_address, R.id.cl_address_emty, R.id.rl_address, R.id.sb_yuyueshijian, R.id.sb_coupon, R.id.tv_final_price, R.id.btn_submit_order,R.id.sb_jianmian_money})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_check_jigui:
                if (jiGuiPopupWindow.isShowing()) {
                    jiGuiPopupWindow.dismiss();
                } else {
                    if (jiGuiPopupWindow != null) {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 0.7f;
                        getWindow().setAttributes(lp);
                        jiGuiPopupWindow.showAsDropDown(clAddress);
                    }
                }
                break;
            case R.id.cl_address:
            case R.id.cl_address_emty:
                Intent intent = new Intent(this, MineAddressManagementActivity.class);
                intent.putExtra("isConfirm", true);
                startActivityForResult(intent, 80);
                break;
            case R.id.rl_address:
                break;
            case R.id.sb_yuyueshijian:
                /**
                 * 预约时间数据
                 */
                selectApprovedDeliveryTime();

                break;
            case R.id.sb_coupon:
                if (coupondataList!=null&&canteenSumList.size()>0){
                    CouponDialog couponDialog = new CouponDialog(ConfirmOrderActivity.this, coupondataList);
                    couponDialog.show();
                    couponDialog.setOnGoodsOrderListener(new CouponDialog.OnGoodsOrderListener() {
                        @Override
                        public void onDismiss(String price) {
                            sbCoupon.setRightText(price);
                            couponprice ="0";
                            finalprice = Double.parseDouble(BigDecimalUtils.sub( BigDecimalUtils.div(orderList.getSjjg()+"","100",2),couponprice,2)+"");
                            tvFinalPrice.setText("￥" + BigDecimalUtils.sub( BigDecimalUtils.div(orderList.getSjjg()+"","100",2),couponprice,2));
                            couponID="";
                        }

                        @Override
                        public void onBuyNow(String price,String couponId) {

                            sbCoupon.setRightText(price);
                            couponprice = price;

                            finalprice = Double.parseDouble(BigDecimalUtils.sub( BigDecimalUtils.div(orderList.getSjjg()+"","100",2),couponprice,2)+"");
                           if (Double.parseDouble(BigDecimalUtils.sub( BigDecimalUtils.div(orderList.getSjjg()+"","100",2),couponprice,2)+"") >=0){
                               finalprice = Double.parseDouble(BigDecimalUtils.sub( BigDecimalUtils.div(orderList.getSjjg()+"","100",2),couponprice,2)+"");
                               tvFinalPrice.setText("￥" + BigDecimalUtils.sub( BigDecimalUtils.div(orderList.getSjjg()+"","100",2),couponprice,2));
                           }else {
                               finalprice=0;
                               tvFinalPrice.setText("￥" + "0");
                           }

                            couponID = couponId;
                        }
                    });
                }else {

                }

                break;
            case R.id.tv_final_price:
                break;
            case R.id.sb_jianmian_money:
                break;

            case R.id.btn_submit_order:
                if (BtnUtils.isFastClick()) {
                    if (tvAddress.getText().toString().isEmpty()) {
                        toast("请选择收货地址");
                        return;
                    }
//                支付
                    for (int i = 0; i < datatwoList.size(); i++) {
                        infosList.clear();
                        infosList.add(datatwoList.get(pos).getBeizhu());
                    }
                    for (int i = 0; i < datathreeList.size(); i++) {
                        cartIdsList.clear();
                        cartIdsList.add(datathreeList.get(pos).getCartId() + "");
                    }
                    infos = CourseUtils.listToString1(infosList);
                    if (!yytime.isEmpty()) {

                        placeAnOrder();
                    } else {
                        placeAnOrder1();
                    }

//                    startActivity(new Intent(this, PayActivity.class).putExtra("cartIds", cartIdS).putExtra("yhj", couponID).putExtra("zzfj", finalprice+"").putExtra("addressid", addressId).putExtra("merchantids", CourseUtils.listToString1(timeList)).putExtra("infos", CourseUtils.listToString1(infosList)).putExtra("appointmentTime", yytime));
//

                }
                break;
        }
    }
    private void UpdateAddress() {

        EasyHttp.post(this)
                .api(new UpdateAdderssApi().setSchooleId(SPUtil.get(this, IntentKey.ADDRESSID, "")).setUserId(SPUtil.get(this, IntentKey.USERID, "")).setName(userName).setPhone(tvPhone.getText().toString()).setAddressid(addressId).setPatientia(patientia).setCabinetryId(cabinetryId)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
//
                toast(data.getList());


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    public  String listToString1(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    private void placeAnOrder() {

        infosList.clear();
        timeList.clear();
        for (int i = 0; i < orderList.getCanteens().size(); i++) {
            for (int j = 0; j < orderList.getCanteens().get(i).getMerchant().size(); j++) {
                infosList.add(orderList.getCanteens().get(i).getMerchant().get(j).getBeizhu());
                timeList.add(orderList.getCanteens().get(i).getMerchant().get(j).getMerchantId() + "");
            }

            }
        EasyHttp.post(this)
                .api(new PlaceAnOrderApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setAddressid(addressId).setYhj(couponID).setAppointmentTime(yytime+":00").setCartIds(cartIdS).setInfos(CourseUtils.listToString1(infosList)).setMerchantids(CourseUtils.listToString1(timeList)).setZzfj(BigDecimalUtils.mul(finalprice+"","100",0)+"")
//                        .setPaymentPlatform(paymentPlatform)
                ).request(new HttpCallback<AddOrderBean>(this) {

            @Override
            public void onSucceed(AddOrderBean data) {
//
                if (data.getError() != null) {
                    if (data.getError() == 0) {

//
                        finish();
                    } else {

                        toast(data.getMsg());
                    }
                } else if (data.getErrorCode() != null) {
                    if (data.getErrorCode() == 0) {
                        startActivity(new Intent(ConfirmOrderActivity.this, PayActivity.class).putExtra("orderNumber", data.getOrderNum()).putExtra("zzfj",finalprice+""));


                    } else {
                        toast(data.getMsg());

                    }
                }
            }

            @Override
            public void onFail(Exception e) {
//                super.onFail(e);
                toast( "系统错误");

            }
        });
    }

    private void placeAnOrder1() {
        infosList.clear();
        timeList.clear();
        for (int i = 0; i < orderList.getCanteens().size(); i++) {
            for (int j = 0; j < orderList.getCanteens().get(i).getMerchant().size(); j++) {
                infosList.add(orderList.getCanteens().get(i).getMerchant().get(j).getBeizhu());
                timeList.add(orderList.getCanteens().get(i).getMerchant().get(j).getMerchantId() + "");
            }

            }
        EasyHttp.post(this)
                .api(new PlaceAnOrderApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setAddressid(addressId).setYhj(couponID).setCartIds(cartIdS).setInfos(CourseUtils.listToString1(infosList)).setMerchantids(CourseUtils.listToString1(timeList)).setZzfj(BigDecimalUtils.mul(finalprice+"","100",0)+"")
//                        .setPaymentPlatform(paymentPlatform)
                ).request(new HttpCallback<AddOrderBean>(this) {

            @Override
            public void onSucceed(AddOrderBean data) {
//

                if (data.getError() != null) {
                    if (data.getError() == 0) {

                    } else {

                        toast(data.getMsg());
                    }
                } else if (data.getErrorCode() != null) {
                    if (data.getErrorCode() == 0) {
                        startActivity(new Intent(ConfirmOrderActivity.this, PayActivity.class).putExtra("orderNumber", data.getOrderNum()).putExtra("zzfj",finalprice+""));
//
                    } else {
                      toast(  data.getMsg());

                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 888 && requestCode == 80) {
            Bundle bundle = data.getExtras();


            if (bundle != null)
                addressBean = (SelectAddressServiceeBean.ListBean) bundle.getSerializable("addressBean");
            userName=addressBean.getName();
            tvUser.setText("收货人："+addressBean.getName());
            tvPhone.setText(addressBean.getPhone());
            tvAddress.setText("收货地址："+addressBean.getCabinetryName());
            addressId = addressBean.getTheGoodsId()+"";
            clAddress.setVisibility(View.VISIBLE);
            clAddressEmty.setVisibility(View.GONE);
            patientia=addressBean.getPatientia()+"";
            Log.e(TAG, "onActivityResult: " + patientia);
        } else if (resultCode == 666 && requestCode == 90) {

            Bundle bundle = data.getExtras();
            String Remark = null;
            String merchantId=null;
            if (bundle != null) {
                merchantId = bundle.getString("merchantId");
                Remark = bundle.getString("Remark");
                for (int i = 0; i < orderList.getCanteens().size(); i++) {
                    for (int j = 0; j < orderList.getCanteens().get(i).getMerchant().size(); j++) {
                        if (orderList.getCanteens().get(i).getMerchant().get(j).getMerchantId().equals(Integer.parseInt(merchantId))) {
                            orderList.getCanteens().get(i).getMerchant().get(j).setBeizhu(Remark);
                        }
                    }
                }
//            datatwoList.get(Integer.parseInt(canteenId)).setBeizhu(Remark);
                oneAdapter.notifyDataSetChanged();
            }
        }
    }
    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode()== EvenConstant.PAYSTAUTS){
//
            finish();
        }
    }
}
